package m.permission.util;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import m.Config;
import m.framework.controller.ControllerMethod;
import m.framework.controller.Task;
import m.framework.controller.UrlParser;
import m.framework.dao.selector.PageRecord;
import m.framework.enums.FileType;
import m.framework.exception.SystemException;
import m.framework.template.TemplateUtil;
import m.framework.utils.ClassUtil;
import m.framework.utils.FileUtil;
import m.framework.utils.StringUtil;
import m.framework.web.view.Html;

/**将查询对象转成excel的工具类*/
public class QueryToExcel {
	private String action;
	private String forwardPage;

	/**生成excel
	 * @param file 要生成的文件名
	 * @param pageRecord 数据
	 * */
	public List<List<String>> createExcelContent(PageRecord pageRecord) {
		ControllerMethod method = UrlParser.getMethod(action);
		String template = method.viewName(forwardPage);
		template=Config.webapp()+"/WEB-INF/template"+template+".jsp";
		String text=FileUtil.getText(template);
		
		//将在html显示的换成适合在excel里显示的
		template=template.replaceAll("HtmlTable", "Excel");
		StringWriter sw = new StringWriter();

		Object[] object = pageObject(method,pageRecord);
		TemplateUtil.evaluate(sw, text, object);
		String content = sw.toString();
		List<List<String>> list = parseQueryTable(content);
		return list;
	}
	
	public String fileName(){
		ControllerMethod method =UrlParser.getMethod(action);
		Task task= method.getController().getClass().getAnnotation(Task.class);
		String name= task.value();
		return StringUtil.getFirstBefore(name, ",")+FileType.excel.getExt();
	}

	private Object[] pageObject(ControllerMethod method,PageRecord pageRecord) {
		List list=new ArrayList();
		list.add(pageRecord);
		List obj = method.addDefault(list);
		Object[] pageObject = new Object[obj.size()];
		for (int i = 0; i < obj.size(); i++) {
			pageObject[i] = obj.get(i);
		}

		Map html = new HashMap();
		html.put("html", htmlForExcel());
		// 将html对象替换掉,因为他的show方法会将特殊字符过滤
		pageObject[pageObject.length - 1] = html;

		return pageObject;
	}

	private Html htmlForExcel() {
		return new Html() {
			public String showRemark(String value) {
				return value;
			}

			public String show(Object obj) {
				String str = ClassUtil.toString(obj);
				if (StringUtil.isEmpty(str)) {
					return "";
				}
				return super.show(obj);
			}
		};
	}

	/**将查询结果页面转成list
	 * 通过提取<table class="list"></list>里的信息
	 * */
	public List<List<String>> parseQueryTable(String html) {
		String table = this.htmlToTable(html);
		String[] title = this.title(table);
		List<String[]> content = this.content(table);

		List result = new ArrayList();
		result.add(createRow(title, title));
		for (String[] c : content) {
			List row = createRow(title, c);
			result.add(row);
		}
		return result;
	}

	private List createRow(String[] title, String[] c) {
		List row = new ArrayList();
		for (int i = 0; i < title.length; i++) {
			if (title[i].equals("序号")) {
				continue;
			}
			if (title[i].equals("操作")) {
				continue;
			}
			row.add(c[i]);
		}
		return row;
	}

	/**解析出table里除了表头以外的内容*/
	private List<String[]> content(String table) {
		String body = StringUtil.pickUpFirst(table, "</thead>(.+?)</table>");
		List list = new ArrayList();
		List<String> trs = StringUtil.pickUp(body, "<tr(.+?)</tr>");
		for (String tr : trs) {
			List<String> tds = StringUtil.pickUp(tr, "<td(.+?)</td>");
			String[] s = new String[tds.size()];
			for (int i = 0; i < s.length; i++) {
				s[i] = tds.get(i).replaceAll(StringUtil.REG_HTML_TAG, "");
			}
			list.add(s);
		}

		return list;
	}

	/**
	 * 从这里面提取出表头
	 * ...<thead><tr>
			<th>序号<img src=''></th>
			<th>...</th>
		</tr></thead>...
	 * **/
	private String[] title(String table) {
		String title = StringUtil.pickUpFirst(table, "<thead>(.+?)</thead>");
		List<String> titles = StringUtil.pickUp(title, "<th>(.+?)</th>");
		String[] result = new String[titles.size()];
		for (int i = 0; i < result.length; i++) {
			result[i] = titles.get(i).replaceAll(StringUtil.REG_HTML_TAG, "");
		}
		return result;
	}

	private String htmlToTable(String html) {
		int begin = html.indexOf("<table class=\"list\"");
		if (begin == -1) {
			throw new SystemException("查询界面格式不正确:" + html);
		}
		int end = html.lastIndexOf("</table>") + "</table>".length();
		return html.substring(begin, end);
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getForwardPage() {
		return forwardPage;
	}

	public void setForwardPage(String forwardPage) {
		this.forwardPage = forwardPage;
	}

}
